package com.itheima.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.atomic.AtomicInteger;

@WebFilter("/demo")
public class FilterDemo1 implements Filter {
    //1. 在filter成员位置定义阈值变量 ：
    private static final int MAX_COUNT = 5;
    //2. 在filter成员位置定义计数器：
    private AtomicInteger filterCount = new AtomicInteger(0);

    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;


        //   判断计数器中计数是否大于阈值

        if (filterCount.get() >= 5) {
            //   - 是：请求转发到 `index.jsp` 排队页面
            request.getRequestDispatcher("/index.jsp").forward(request, response);
        } else {
            //   - 否：完成以下步骤
            //     1. 计数器加一’；

            System.out.println(filterCount.incrementAndGet());
            //     2. 放行
            chain.doFilter(request, response);
            //     3. 计数器减一
            System.out.println(filterCount.decrementAndGet());

        }



    }

    public void init(FilterConfig config) throws ServletException {

    }

}